import 'dart:async';

import 'package:enjoy_plus_three/utils/http.dart';
import 'package:enjoy_plus_three/utils/toast.dart';
import 'package:enjoy_plus_three/utils/token.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
// 实现倒计时
  int _countdown = 60; // 倒计时的时长
  bool _isCountingDown = false; // 是否正在倒计时 (标志 - 防止重复点击)
  Timer? _timer;
  //开启倒计时效果
  _startCountDown() {
    // 如果正在倒计时, 终止程序运行
    if (_isCountingDown) return;
    // 执行倒计时逻辑
    _isCountingDown = true; // 标记倒计时的状态是进行中
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 1) {
          _countdown--;
        } else {
          _countdown = 60;
          _isCountingDown = false;
          _timer!.cancel(); // 关闭定时器
        }
      });
    });
  }

//创建输入框控制器
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();

//获取验证码
void _getVerificationCode() async {
  // 判断手机号是否为空
  if (_phoneController.text.isEmpty) {
    return ToastUtil.showError('请输入手机号');
  }
  // 判断手机号格式是否正确
  RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
  if (!regExp.hasMatch(_phoneController.text)) {
    return ToastUtil.showError('手机号格式不正确');
  }
  //调用获取验证码接口
  var res = await http.get('/code',params: {
    'mobile':_phoneController.text
  });
  if(res['code'] != 10000) return ToastUtil.showError('获取验证码失败');
  ToastUtil.showSuccess('获取验证码成功');

  //开启倒计时效果
  _startCountDown();

  //延迟执行
  Future.delayed(const Duration(seconds: 3),(){
    //倒计时
   _codeController.text = res['data']['code'];
  });

}

 void _submit() async {
  if(_phoneController.text.isEmpty){
    return ToastUtil.showError('请输入手机号');
  }
  RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
  if(!regExp.hasMatch(_phoneController.text)){
    return ToastUtil.showError('请输入正确的手机号');
  }
  if(_codeController.text.isEmpty){
    return ToastUtil.showError('请输入验证码');
  }
  if(_codeController.text.length != 6){
    return ToastUtil.showError('请输入6位验证码');
  }
  RegExp regExp2 = RegExp(r'^\d{6}$');
  if(!regExp2.hasMatch(_codeController.text)){
    return ToastUtil.showError('请输入正确的验证码');
  }

  try{
    var res = await http.post('/login', {
      'mobile':_phoneController.text,
      'code':_codeController.text
    });
    if(res['code'] != 10000) return ToastUtil.showError('登录失败');
    
    //存储token
    TokenManager().setToken(res['data']['token']);
    ToastUtil.showSuccess('登录成功');

    //返回上一页
    _timer!.cancel(); //清除定时器
    // ignore: use_build_context_synchronously
    Navigator.pop(context);
  }catch(e){
    ToastUtil.showError('登录失败');
  }
 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('登录'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              const Row(
                children: [
                  Text('登录',
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold))
                ],
              ),
              const SizedBox(height: 10),
              const Row(
                children: [
                  Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))
                ],
              ),
              const SizedBox(height: 30),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: TextField(
                      decoration: const InputDecoration(
                        labelText: '手机号',
                        hintText: '请输入手机号',
                      ),
                      controller: _phoneController,
                      keyboardType: TextInputType.phone,
                      maxLength: 11,
                      style: const TextStyle(fontSize: 16),
                    ),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shadowColor: Colors.transparent,
                      foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      // 开启倒计时效果
                      _getVerificationCode();
                    },
                    child: _isCountingDown
                        ? Text(
                            '$_countdown s后重新获取',
                            style: const TextStyle(color: Colors.red),
                          )
                        : const Text('获取验证码'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              TextField(
                decoration: const InputDecoration(
                  labelText: '验证码',
                  hintText: '请输入6位验证码',
                ),
                controller: _codeController,
                keyboardType: TextInputType.number,
                maxLength: 6,
                style: const TextStyle(fontSize: 16),
              ),
              const SizedBox(height: 8),
              const Row(children: [
                Text('未注册手机号经验证后将自动登录',
                    style: TextStyle(fontSize: 12, color: Colors.grey)),
              ]),
              const SizedBox(height: 50),
              Row(children: [
                Expanded(
                    child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _submit();
                  },
                  child: const Text('登录',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                ))
              ])
            ])));
  }
}
